<?php

namespace App\Http\Controllers\Platform\Setting;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Common\DataResource;
use App\Models\Game\Platform\Org\AccessKey;
use App\Models\Game\Platform\Org\Wallet;

class AccessKeyController extends Controller
{

    /**
     * 获取数据
     */
    public function getData(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64'
        ]);
        $platCode = $request->input('plat_code');

        $data = AccessKey::withTrashed()->where('plat_code', $platCode)->firstOrFail();

        return new DataResource($data);
    }

    /**
     * 更新或创建数据
     *
     * @param string $platCode
     */
    public function updateOrCreate(Request $request)
    {
        $params = $this->validate($request, [
            'plat_code' => 'required|string|max:64'
        ]);

        $data = AccessKey::withTrashed()->updateOrCreate(
            $params, AccessKey::makeAccessKey()
        );

        // 同步 AccessKey
        if (!is_null(
            $wallet = Wallet::withTrashed()->where('plat_code', $params['plat_code'])->first()
        )) {
            // 修改钱包 AccessKey
            $wallet->fill($data->only('access_key_id', 'access_key_secret'));
            // 保存钱包 AccessKey
            $wallet->save();
            // 通知游戏端配置修改
            $wallet->syncGameService();
        }

        return new DataResource($data);
    }

    /**
     * 删除数据
     *
     * @param string $platCode
     */
    public function destroy(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64'
        ]);
        $platCode = $request->input('plat_code');

        $data = AccessKey::where('plat_code', $platCode)->firstOrFail();
        $data->delete();

        return new DataResource($data);
    }

    /**
     * 恢复删除
     *
     * @param string $platCode
     */
    public function restore(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64'
        ]);
        $platCode = $request->input('plat_code');

        $data = AccessKey::withTrashed()->where('plat_code', $platCode)->firstOrFail();
        $data->restore();

        return new DataResource($data);
    }

}
